package com.tencent.qf.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.tencent.qf.common.activityplatform.ActivityPlatformUtils;
import com.tencent.qf.common.activityplatform.ActivityPlatfromApiPath;
import com.tencent.qf.common.exception.ErrorCode;
import com.tencent.qf.common.pojo.ActivityPlatformHttpResult;
import com.tencent.qf.common.pojo.HttpResult;
import com.tencent.qf.user.config.properties.LotteryProperties;
import com.tencent.qf.user.config.properties.UserInfoProperties;
import com.tencent.qf.user.dto.UserInfoDetail;
import com.tencent.qf.user.dto.request.AvailableQualificationCountActivityRequest;
import com.tencent.qf.user.dto.request.AvailableQualificationCountRequest;
import com.tencent.qf.user.dto.request.GetAwardDescRequest;
import com.tencent.qf.user.dto.request.IssueGoldRequest;
import com.tencent.qf.user.dto.request.QueryAwardPoolInfoByOrderAmtRequest;
import com.tencent.qf.user.dto.request.QueryGoldDetailBySerialNoRequest;
import com.tencent.qf.user.dto.request.QueryOrderPointsReq;
import com.tencent.qf.user.dto.request.SpecialAreaDisplayRequest;
import com.tencent.qf.user.dto.request.SpecialAreaInfoReq;
import com.tencent.qf.user.dto.request.TaskAwardDataRequest;
import com.tencent.qf.user.dto.request.TaskCompleteEventReq;
import com.tencent.qf.user.dto.request.UserInfoByUidUnionIdRequest;
import com.tencent.qf.user.dto.request.UserInfoDTO;
import com.tencent.qf.user.dto.request.UserUnSucceedTaskRequest;
import com.tencent.qf.user.dto.response.AvailableQualificationCountDTO;
import com.tencent.qf.user.dto.response.AwardDescResponse;
import com.tencent.qf.user.dto.response.AwardPoolInfoResponse;
import com.tencent.qf.user.dto.response.GoldDetailResponse;
import com.tencent.qf.user.dto.response.OrderPointsResp;
import com.tencent.qf.user.dto.response.SpecialAreaDisplayResponse;
import com.tencent.qf.user.dto.response.SpecialAreaInfoDTO;
import com.tencent.qf.user.dto.response.TaskAwardData;
import com.tencent.qf.user.dto.response.UserPaymentCountDTO;
import com.tencent.qf.user.dto.response.UserUnSucceedTask;
import com.tencent.qf.user.enums.TaskTypeEnum;
import com.tencent.qf.user.service.ActivityPlatformService;
import com.tencent.qf.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.util.concurrent.ListenableFuture;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author liuxuan
 * @time 2022/12/21 10:22
 */
@Service
@Slf4j
public class ActivityPlatformServiceImpl implements ActivityPlatformService {
    @Autowired
    private ActivityPlatformUtils activityPlatformUtils;

    @Autowired
    private UserService userService;

    @Resource
    private LotteryProperties lotteryProperties;
    @Resource
    private KafkaTemplate kafkaTemplate;

    @Value("${spring.kafka.topic.task-complete}")
    public String taskCompleteTopic;
    @Value("${spring.kafka.topic.care-Wxpub}")
    public String careWxpubTopic;

    @Resource
    private UserInfoProperties userInfoProperties;

    /**
     * 任务完成事件通知
     *
     * @param request
     * @return
     */
    @Override
    public HttpResult taskCompleteEvent(TaskCompleteEventReq request) {

        ListenableFuture sendCareWxpub = null, sendTaskComplete = null;

        if (Objects.equals(request.getTaskType(), TaskTypeEnum.Care_Wxpub.getType())) {
            sendCareWxpub = kafkaTemplate.send(careWxpubTopic, JSON.toJSONString(request));
        }
        sendTaskComplete = kafkaTemplate.send(taskCompleteTopic, JSON.toJSONString(request));

        try {
            if (sendCareWxpub != null) {
                Object o = sendCareWxpub.get(2L, TimeUnit.SECONDS);
                log.info("关注公众号,发送Kafka消息结果：{}", JSON.toJSONString(o));
            }
            if (sendTaskComplete != null) {
                Object o = sendTaskComplete.get(2L, TimeUnit.SECONDS);
                log.info("任务完成事件通知,发送Kafka消息结果：{}", JSON.toJSONString(o));
            }
        } catch (Exception e) {
            log.error("任务完成事件通知异常：", e);
            throw new RuntimeException(e);
        }
        return HttpResult.success(null);
    }

    /**
     * 发放金币
     *
     * @param request
     * @return
     */
    @Override
    public ActivityPlatformHttpResult<Boolean> issueGold(IssueGoldRequest request) {
        String response = activityPlatformUtils.post(request, ActivityPlatfromApiPath.issueGold);
        if(!StringUtils.hasText(response)){
            return ActivityPlatformHttpResult.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode().toString(), ErrorCode.INTERNAL_SERVER_ERROR.getMsg());
        }
        ActivityPlatformHttpResult<Boolean> httpResult = JSON.parseObject(response, new TypeReference<ActivityPlatformHttpResult<Boolean>>() {
        });
        return httpResult;
    }


    /**
     * 通过流水号查询
     *
     * @param request request
     * @return
     */
    @Override
    public ActivityPlatformHttpResult<GoldDetailResponse> queryGoodsDetailBySerialNo(QueryGoldDetailBySerialNoRequest request) {
        String response = activityPlatformUtils.post(request, ActivityPlatfromApiPath.queryGoldDetailBySerialNo);

        if(!StringUtils.hasText(response)){
            return ActivityPlatformHttpResult.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode().toString(), ErrorCode.INTERNAL_SERVER_ERROR.getMsg());
        }
        return JSON.parseObject(response, new TypeReference<ActivityPlatformHttpResult<GoldDetailResponse>>() {
        });
    }

    @Override
    public ActivityPlatformHttpResult<AvailableQualificationCountDTO> getAvailableQualificationCount(AvailableQualificationCountRequest request) {
        UserInfoByUidUnionIdRequest userInfoByUidUnionIdRequest = new UserInfoByUidUnionIdRequest();
        userInfoByUidUnionIdRequest.setUid(request.getUid());
        userInfoByUidUnionIdRequest.setSaasId(userInfoByUidUnionIdRequest.getSaasId());
        UserInfoDetail userInfoDetail = userService.userInfoByUidUnionId(userInfoByUidUnionIdRequest).getData();
        // 获取用户分层
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUnionId(userInfoDetail.getUnionId());
        String userType = userService.userPaymentInfo(userInfoDTO).getData().getUserType();

        if(!"4".equals(userType)){
            AvailableQualificationCountDTO result = AvailableQualificationCountDTO.builder().availableCount(0).isActivityOnline(false).build();
            return ActivityPlatformHttpResult.success(result);
        }

        AvailableQualificationCountActivityRequest activityRequest= AvailableQualificationCountActivityRequest.builder().uid(userInfoDetail.getUid())
                .accountType(userInfoDetail.getType())
                .levelId(userInfoDetail.getLevelId())
                .userType(userType)
                .build();

        String response = activityPlatformUtils.post(activityRequest, ActivityPlatfromApiPath.queryAvailableQualificationCount);

        if(!StringUtils.hasText(response)){
            return ActivityPlatformHttpResult.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode().toString(), ErrorCode.INTERNAL_SERVER_ERROR.getMsg());
        }
        return JSON.parseObject(response, new TypeReference<ActivityPlatformHttpResult<AvailableQualificationCountDTO>>() {
        });
    }

    @Override
    public HttpResult<AwardDescResponse> getAwardDesc(GetAwardDescRequest request) {
        AwardDescResponse awardDescResponse = new AwardDescResponse();
        String awardDesc = "";
        if (!lotteryProperties.getEnable()) {
            awardDescResponse.setAwardDesc(awardDesc);
            return HttpResult.success(awardDescResponse);
        }
        // 获取用户分层
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUnionId(request.getUnionId());
        UserPaymentCountDTO userPaymentCountDTO = userService.userPaymentInfo(userInfoDTO).getData();

        // 获取等级等信息
        UserInfoByUidUnionIdRequest userInfoByUidUnionIdRequest = new UserInfoByUidUnionIdRequest();
        userInfoByUidUnionIdRequest.setUnionId(request.getUnionId());
        userInfoByUidUnionIdRequest.setSaasId(lotteryProperties.getRootSaasId());
        UserInfoDetail userInfoDetail = userService.userInfoByUidUnionId(userInfoByUidUnionIdRequest).getData();

        // 获取订单信息
        JSONObject orderInfo = JSONObject.parseObject(request.getOrderData());

        //构造请求
        QueryAwardPoolInfoByOrderAmtRequest req = QueryAwardPoolInfoByOrderAmtRequest.builder().orderAmount(orderInfo.getIntValue("estimatedDistributeAmount"))
                .unionId(request.getUnionId()).userLevel(userInfoDetail.getLevelId()).userPaymentInfo(userPaymentCountDTO)
                .uid(userInfoDetail.getUid()).userType(String.valueOf(userInfoDetail.getType()))
                .orderId(orderInfo.getString("planId"))
                .orderInfo(request.getOrderData()).build();

        try {
            String response = activityPlatformUtils.post(req, ActivityPlatfromApiPath.queryAwardPoolInfoByOrderAmt);
            if (!StringUtils.hasText(response)) {
                return HttpResult.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode(), ErrorCode.INTERNAL_SERVER_ERROR.getMsg());
            }
            ActivityPlatformHttpResult<AwardPoolInfoResponse> result = JSON.parseObject(response, new TypeReference<ActivityPlatformHttpResult<AwardPoolInfoResponse>>() {
            });
            if (result.getData() != null) {
                AwardPoolInfoResponse data = result.getData();
                awardDesc = lotteryProperties.getAwardDesc().replace("{maxAwardPrice}", data.getMaxAwardPrice());
            }
        }catch (Exception e){
            log.error("请求活动平台接口失败，unionId : " + request.getUnionId() + ", amount: " + orderInfo.getIntValue("estimatedDistributeAmount") + ",error: ", e);
        }
        awardDescResponse.setAwardDesc(awardDesc);
        awardDescResponse.setPagePath(lotteryProperties.getPagePath());
        awardDescResponse.setMiniprogramAppid(lotteryProperties.getMiniprogramAppid());
        return HttpResult.success(awardDescResponse);
    }

    @Override
    public ActivityPlatformHttpResult<List<OrderPointsResp>> queryOrderPointsBatch(QueryOrderPointsReq request) {
        String response = activityPlatformUtils.post(request, ActivityPlatfromApiPath.queryPointsByOrderId);

        if(!StringUtils.hasText(response)){
            return ActivityPlatformHttpResult.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode().toString(), ErrorCode.INTERNAL_SERVER_ERROR.getMsg());
        }
        return JSON.parseObject(response, new TypeReference<ActivityPlatformHttpResult<List<OrderPointsResp>>>() {
        });
    }

    @Override
    public ActivityPlatformHttpResult<TaskAwardData> queryUserTaskAwardData(TaskAwardDataRequest request) {
        try {
            String response = activityPlatformUtils.post(request, ActivityPlatfromApiPath.userTaskAwardData);

            if (!StringUtils.hasText(response)) {
                return ActivityPlatformHttpResult.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode().toString(), ErrorCode.INTERNAL_SERVER_ERROR.getMsg());
            }
            return JSON.parseObject(response, new TypeReference<ActivityPlatformHttpResult<TaskAwardData>>() {
            });
        }catch (Exception e){
            // C端没上线或者活动未开始, 返回空数据
            TaskAwardData taskAwardData = new TaskAwardData();
            taskAwardData.setTaskIncome(new TaskAwardData.TaskIncome());
            taskAwardData.setWaitTaskPhaseData(new ArrayList<>());
            return ActivityPlatformHttpResult.success(taskAwardData);
        }
    }

    @Override
    public ActivityPlatformHttpResult<List<UserUnSucceedTask>> queryUserUnSucceedTask(UserUnSucceedTaskRequest request) {
        UserInfoByUidUnionIdRequest userInfoByUidUnionIdRequest = new UserInfoByUidUnionIdRequest();
        userInfoByUidUnionIdRequest.setUid(request.getIrisUid());
        userInfoByUidUnionIdRequest.setSaasId(lotteryProperties.getRootSaasId());
        UserInfoDetail userInfoDetail = userService.userInfoByUidUnionId(userInfoByUidUnionIdRequest).getData();
        if(userInfoDetail == null){
            log.info("获取用户未完成任务，用户不存在");
            return ActivityPlatformHttpResult.success(Collections.emptyList());
        }
        try {
            request.setLevelId(userInfoDetail.getLevelId());
            request.setType(String.valueOf(userInfoDetail.getType()));
            request.setUnionId(userInfoDetail.getUnionId());
            String response = activityPlatformUtils.post(request, ActivityPlatfromApiPath.userUnSuccessTask);

            if (!StringUtils.hasText(response)) {
                return ActivityPlatformHttpResult.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode().toString(), ErrorCode.INTERNAL_SERVER_ERROR.getMsg());
            }
            return JSON.parseObject(response, new TypeReference<ActivityPlatformHttpResult<List<UserUnSucceedTask>>>() {
            });
        }catch (Exception e){
            // C端没上线或者活动未开始, 返回空数据
            return ActivityPlatformHttpResult.success(Collections.emptyList());
        }
    }

    @Override
    public ActivityPlatformHttpResult<List<SpecialAreaInfoDTO>> getSpecialAreaInfo(SpecialAreaInfoReq request) {
        try {
            //uid和unionId=>levelId
            UserInfoByUidUnionIdRequest uidUnionIdRequest = UserInfoByUidUnionIdRequest.builder()
                    .unionId(request.getUnionId()).uid(request.getUid()).saasId(userInfoProperties.getRootSaasId()).build();
            HttpResult<UserInfoDetail> userDetailResult = userService.userInfoByUidUnionId(uidUnionIdRequest);
            if (Objects.isNull(userDetailResult.getData())){
                log.info("用户信息不存在,uid={},unionId={}", request.getUid(), request.getUnionId());
                return ActivityPlatformHttpResult.error(ErrorCode.USER_NOT_EXIST.getCode().toString(), ErrorCode.USER_NOT_EXIST.getMsg());
            }
            request.setLevelId(userDetailResult.getData().getLevelId());
            request.setUserType(userDetailResult.getData().getType());
            String response = activityPlatformUtils.post(request, ActivityPlatfromApiPath.specialAreaInfo);

            if (!StringUtils.hasText(response)) {
                return ActivityPlatformHttpResult.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode().toString(), ErrorCode.INTERNAL_SERVER_ERROR.getMsg());
            }
            return JSON.parseObject(response, new TypeReference<ActivityPlatformHttpResult<List<SpecialAreaInfoDTO>>>() {
            });
        }catch (Exception e){
            // C端没上线或者活动未开始, 返回空数据
            return ActivityPlatformHttpResult.success(Collections.emptyList());
        }
    }

    @Override
    public ActivityPlatformHttpResult<SpecialAreaDisplayResponse> specialAreaDisplay(String specialAreaId, String uid) {
        try {

            String response = activityPlatformUtils.post(new SpecialAreaDisplayRequest().setSpecialAreaId(specialAreaId).setUid(uid), ActivityPlatfromApiPath.queryUserDisplayQualification);

            if (!StringUtils.hasText(response)) {
                return ActivityPlatformHttpResult.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode().toString(), ErrorCode.INTERNAL_SERVER_ERROR.getMsg());
            }
            return JSON.parseObject(response, new TypeReference<ActivityPlatformHttpResult<SpecialAreaDisplayResponse>>() {
            });
        }catch (Exception e){
            // C端没上线或者活动未开始, 返回空数据
            SpecialAreaDisplayResponse response = new SpecialAreaDisplayResponse();
            response.setHasQualification(false);
            return ActivityPlatformHttpResult.success(response);
        }
    }


}
